package com.xusheng.cli.controller.open;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Slf4j
public abstract class BaseNotifyController {

    @Resource
    private Redisson redisson;
    private final String LOCK = "GAME_PAY_NOTIFY_FLAG:";

    protected void notifyAsync(HttpServletRequest request, HttpServletResponse response, String orderNo) {
        boolean lock = false;
        String lockName = LOCK.concat(orderNo);
        RLock distributedLock = redisson.getLock(lockName);
        try {
            if (lock = distributedLock.tryLock(0, 10, TimeUnit.SECONDS)) {
                log.info("{} 获取锁成功任务开始执行", lockName);
                doNotifyBusiness(request, response, orderNo);
            }
        } catch (Exception e) {
            log.error("{} 任务执行出错", e, lockName);
        } finally {
            if (lock) {
                log.info("{} 任务执行结束", lockName);
                try {
                    distributedLock.unlock();
                } catch (Exception e) {
                    log.error("{} 锁释放失败", lockName);
                }
            }
        }
    }

    protected abstract void doNotifyBusiness(HttpServletRequest request, HttpServletResponse response, String orderNo);
}
